import { Component, Input, OnInit, ViewChild } from '@angular/core';
import { SFSchema } from '@delon/form';
import { ApiService } from '@core/services/api';
import { HttpClient } from '@angular/common/http';
import { NzMessageService, NzModalRef, NzModalService,UploadFile } from 'ng-zorro-antd';
import { ColumnType, SPage, TablePageComponent } from '@shared/components/table-page/table-page.component';
import { NzTabPosition } from 'ng-zorro-antd/tabs';
import { TakephotoComponent } from '@shared/components/takephoto/takephoto.component';

@Component({
  selector: 'app-user-edit',
  templateUrl: './user-edit.component.html',
  styles: []
})
export class UserEditComponent implements OnInit {
  //房间信息列表
  @ViewChild('st', { static: false }) st: TablePageComponent;
  //用户信息
  @Input()type: 0 | 1;
  @Input()
  set _param(value) {
    console.log(value);
    if (!value) return;
    this.id = value.id;
    this.param = value;
    this.param.infoAge=this.analyzeIDCard(this.param.papersNumber);
    this.param.infoBirthday=this.getBirthdayFromIdCard(this.param.papersNumber);

    if(this.param.infoPeoplePhoto) {
      this.previewImage = this.param.infoPeoplePhoto;
      // this.fileList = [...[{
      //   id: '-1',
      //   status: 'done',
      //   url: this.param.infoPeoplePhoto
      // }]]
      this.show=true
      this.showUpdate=true
      this.avatarUrl=this.param.infoPeoplePhoto
      this.avatarUrl2=this.param.infoPeoplePhoto
    }
  };
  previewImage: string | undefined = '';
  previewVisible = false;
  param: any;
  id:string;
  showForm = false;
  show:boolean=false
  showUpdate:boolean=false
  avatarUrl:string=""
  avatarUrl2:string=""
  maxSize:number=1000;//图片最大为1M
  maxWidth:number=640;
  maxHeight:number=480;
  isAllow:boolean=true;//图片是否超出限制
  config: SPage = {
    columns: [
      {
        index: 'roomFloor',
        title: '所在层数',
      },
      {
        index: 'roomNumber',
        title: '门牌号',
      },
      {
        index: 'roomName',
        title: '房间名称',
      },
      {
        index: 'houseName',
        title: '区域名称',
        width:400
      },
      // {
      //   index: 'roomType',
      //   title: '类型',
      //   // type: ColumnType.tag,
      //   // tag: {
      //   //   0: {text:''},
      //   //   1: {text:''},
      //   // }
      // },
      {
        index: 'roomApprove',
        title: '审批状态',
        type: ColumnType.tag,
        tag: {
          0: {text:'未审批', color: 'red'},
          1: {text:'已审批', color: 'green'},
        }
      },
    ],
    data:[],
    editBtn: [
      
    ],
    ps: 5,
  };
  config2: SPage = {
    columns: [
      {
        index: 'cardNo',
        title: '卡号',
        width:150,
        fFn: (item, columu) => this.delCardZero(item.cardNo),
      },
      {
        index: 'cardType',
        title: '卡类型',
        width:120,
        type: ColumnType.tag,
        tag: {
          1:{text:'IC卡'},
          2:{text:'CPU卡'},
          3:{text:'身份证'},
          4:{text:'居住证'},
          5:{text:'银行卡'},
          6:{text:'APP'},
        },
      },
      {
        index: 'cardStatus',
        title: '状态',
        width:100,
        type: ColumnType.tag,
        tag:{
          0:{text:'未激活',color: 'red'},
          1:{text:'已激活', color: 'green'},
          2:{text:'丢失', color: 'red'},
          3:{text:'损坏', color: 'red'},
          4:{text:'冻结', color: 'red'},
          5:{text:'待缴费', color: 'red'},
          6:{text:'已过期', color: 'red'},
          7:{text:'退卡', color: 'red'},
          9:{text:'其他'}
        },
      },
      {
        index: 'infoName',
        width:100,
        title: '持卡人',
      },
      {
        index: 'infoMobile',
        title: '持卡人手机号',
        width:120,
      },
     
      {
        index: 'houseName',
        title: '详细地址',
        width:300,
      },
      {
        index: 'cardUsingEndTime',
        title: '到期时间',
        width:120,
        
      },
      {
        index: 'infoMobile',
        title: '注销时间',
        width:120,
      },
      {
        index: 'mark',
        title: '备注',
        width:120,
      }
    ],
    data:[],
    ps: 5,
  };
  faceConfig:SPage={
    columns:[
      {
        index: 'faceUrl',
        title: '人脸照片',
        width:80,
        type:ColumnType.img,
        clickFn:(record)=>{
          console.log(record);
          const modal = this.modal.create({
            nzTitle: '人脸照片',
            nzContent: '<img width="100%" src="'+record.faceUrl+'">',
            nzWidth: 800,
            nzFooter: null
          })
        }
      },
      {
        index:'deviceCode',
        title:'门禁SN',
        width:120,
      },
      {
        index:'deviceFac',
        title:'门禁名称',
        width:150
      },
      {
        index:'deviceLocation',
        title:'门禁位置',
        width:400
      },
      {
        index:'faceUploadStatus',
        title:'人脸状态',
        type:ColumnType.tag,
        width:80,
        tag:{
          0:{text:'失败'},
          1:{text:'成功'}
        }
      },
      {
        index:'faceFailureReason',
        title:'失败原因',
        width:80,
        fFn: (item, columu) => {
          if(item.faceUploadStatus == 0){
            return item.faceFailureReason;
          }else if(item.faceUploadStatus == 1){
            return "";
          }
        },
      }
    ],
    data:[],
    editBtn:[
      {title:'重新下发'}
    ],
    ps: 5,
  }
  schema2: SFSchema = {
    properties: {
      deviceId: {
        type: 'string',
        ui:{
          hidden:true
        }
      },
      deviceTag: {
        type: 'boolean',
        title: '小程序开门',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span :8}
        }
      },
      deviceBioAssay: {
        type: 'boolean',
        title: '刷卡开门',
        ui: {
          checkedChildren: '开',
          unCheckedChildren: '关',
          grid: {span: 8}
        }
      },
    },
    "ui": {
      "spanLabelFixed": 150,
      "grid": {
        "span": 24
      }
    },
    required: ["deviceId"]
  };

  fileList: any[] = [
    {
      id: '-1',
      status: 'done',
      url: "../../../../../assets/images/noimg.png"
    }
  ];
  schema: SFSchema = {
    properties: {
      // infoApprovalStatus: {
      //   type: 'string',
      //   title: '审批状态',
      //   readOnly:true,
      //   enum:[
      //     {label: '未审批', value: 0},
      //     {label: '已审批', value: 1}
      //   ],
      //   ui: {
      //     widget: 'select',
      //     grid:{span: 8}
      //   }
      // },
      infoName: {
        type: 'string',
        title: '姓名',
        readOnly:true,
        ui: {
          grid: {span: 8}
        }
      },
      papersNumber: {
        type: 'string',
        title: '身份证号',
        readOnly:true,
        ui: {
          grid: {span: 8}
        }
      },
      infoSex: {
        type: 'string',
        title: '性别',
        readOnly:true,
        enum:[
          {label: '男', value: '1'},
          {label: '女', value: '0'},
          {label: '未说明的性别', value: "9"}
        ],
        ui: {
          widget: 'select',
          grid: {span: 8}
        }
      },
      infoAge :{
        type: 'number',
        title: '年龄',
        readOnly:true,
        ui: {
          grid: {span: 8}
        }
      },
      infoBirthday :{
        type: 'string',
        title: '出生日期',
        readOnly:true,
        ui: {
          grid: {span: 8}
        }
      },
      // infoNationCode: {
      //   type: 'string',
      //   title: '民族代码',
      //   ui: {
      //     grid: {span: 6}
      //   }
      // },
      infoNationName: {
        type: 'string',
        title: '民族',
        readOnly:true,
        ui: {
          grid: {span: 8}
        }
      },
      // infoMaritalStatus: {
      //   type: 'string',
      //   title: '婚姻状况',
      //   readOnly:true,
      //   enum: [
      //     {label: '未婚', value: 10},
      //     {label: '已婚', value: 20},
      //     {label: '初婚', value: 21},
      //     {label: '再婚', value: 22},
      //     {label: '复婚', value: 23},
      //     {label: '丧偶', value: 30},
      //     {label: '离婚', value: 40},
      //     {label: '未说明的婚姻状况', value: 90}
      //   ],
      //   ui: {
      //     widget: 'select',
      //     grid: {span: 8}
      //   }
      // },
      infoMobile: {
        type: 'string',
        title: '联系电话',
        ui: {
          grid: {span: 8}
        }
      },
      // infoEmergencyMobile: {
      //   type: 'string',
      //   title: '紧急联系电话',
      //   ui: {
      //     grid: {span: 8}
      //   }
      // },
      // infoEmail: {
      //   type: 'string',
      //   title: '电子邮件',
      //   readOnly:true,
      //   ui: {
      //     grid: {span: 8}
      //   }
      // },
      // infoCulture: {
      //   type: 'string',
      //   title: '教育水平',
      //   readOnly:true,
      //   ui: {
      //     grid: {span: 8}
      //   }
      // },
      // infoCompanyName: {
      //   type: 'string',
      //   title: '公司名称',
      //   ui: {
      //     grid: {span: 12}
      //   }
      // },
      // infoNativePlace: {
      //   type: 'string',
      //   title: '籍贯',
      //   readOnly:true,
      //   ui: {
      //     grid: {span: 8}
      //   }
      // },
      // infoDwellType: {
      //   type: 'string',
      //   title: '人员常住类型',
      //   readOnly:true,
      //   enum: [
      //     {label: '孤寡', value: 0},
      //     {label: '失能', value: 1},
      //     {label: '津贴', value: 2},
      //     {label: '独居', value: 3},
      //     {label: '子女同居', value: 4},
      //     {label: '养老机构', value: 5},
      //     {label: '配偶同居', value: 6},
      //     {label: '其他', value: 7},
      //   ],
      //   ui: {
      //     widget: 'select',
      //     grid: {span :8}
      //   }
      // },
      papersAddress: {
        type: 'string',
        title: '身份证地址',
        readOnly:true,
      }
    },
    "ui": {
      "spanLabelFixed": 150,
      "grid": {
        "span": 24
      }
    },
    required: ['infoName', 'infoMobile']
  }

  //删除卡号后面的8个0
  delCardZero(num:string):string{
    if(num.length > 8){
      num = num.substring(0,num.length - 8);
    }
    return num;
  }

  handlePreview = async () => {
    this.previewVisible = true;
  };

  getUserInfo(userId: string): Promise<any>{
    return this.http.request<any>('GET', '/core/person/'+userId).toPromise();
  }
  getBase64(img: File, callback: (img: string) => void): void {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result!.toString()));
    reader.readAsDataURL(img);
  }
  handleChange(info: { file: UploadFile }){
    console.log(info);
    //判断图片是否超出1M
   // this.testMaxSize(info.file);
    console.log(this.isAllow)
    // if(this.isAllow){//未超出1M
    //   this.getBase64(info.file!.originFileObj!, (img: string) => {
    //     this.avatarUrl = img;
    //     this.show=true;
    //   });
    // }else{//超出1M,压缩图片
    //   this.getBase64(info.file!.originFileObj!, (img: string) => {
    //     let imgObj=new Image();
    //     imgObj.src=img;
    //     imgObj.onload=()=>{
    //       const { width:originWidth,height:originHeight } = imgObj;
    //       console.log(originHeight,originWidth);
    //       this.compressImg(originWidth,originHeight,imgObj);
    //     }
    //   });
    // }
    this.getBase64(info.file!.originFileObj!, (img: string) => {
      let imgObj=new Image();
      imgObj.src=img;
      imgObj.onload=()=>{
        const { width:originWidth,height:originHeight } = imgObj;
        console.log(originHeight,originWidth);
        this.compressImg(originWidth,originHeight,imgObj);
      }
    });
   
  }

  //等比例缩放，canvas压缩图片
  compressImg(originWidth:number,originHeight:number,img){
    let targetWidth=originWidth;
    let targetHeight=originHeight;
    // 等比例计算超过最大限制时缩放后的图片尺寸
    if (originWidth > this.maxWidth || originHeight > this.maxHeight) {
      if (originWidth / originHeight > 1) {
      // 宽图片
      targetWidth = this.maxWidth
      targetHeight = Math.round(this.maxWidth * (originHeight / originWidth))
      } else {
      // 高图片
      targetHeight = this.maxHeight
      targetWidth = Math.round(this.maxHeight * (originWidth / originHeight))
      }
    }

    console.log(targetHeight,targetWidth);
    // 创建画布
    const canvas = document.createElement('canvas')
    const context = canvas.getContext('2d')
    
    // 设置宽高度为等同于要压缩图片的尺寸
    canvas.width = targetWidth
    canvas.height = targetHeight
    context.clearRect(0, 0, targetWidth, targetHeight)
    //将img绘制到画布上
    context.drawImage(img, 0, 0, targetWidth, targetHeight)
    let base64=canvas.toDataURL("image/jpeg",0.8);
    this.avatarUrl2 = base64;
    this.showUpdate=true;
  }
  
  formSubmit(data) {
    if(data.infoMobile.indexOf("*") != -1){
      this.msg.warning("请输入正确的手机号")
      return
    }
    const body: any = {
      id: data.id,
      infoMobile:data.infoMobile
    };
    this.http.post(this.api.user.updatePerson.url,body).subscribe((res:any) => {
      if (res.status === '200' || res.status === '201') {
        this.msg.success('操作成功');
        this.modalRef.destroy('ok');
      } else {
        this.msg.error(res.message)
      }
    })

  }
   //修改图片
   submit(){
    const body: any = {
      faceBase64:""
    };
    const formData = new FormData();
    if(this.avatarUrl2.indexOf("data:image") != -1){//  代表地址是base64,那么表示用户修改了图片
       body.faceBase64=this.avatarUrl2.replace(/^data:image\/\w+;base64,/, '');
     }
     if(body.faceBase64 == ""){
      this.msg.error("请上传图片!")
      return
     }
     formData.append('personId', this.id);
     formData.append('faceBase64', body.faceBase64);
    this.http.post("/core/person/uploadPeopleFace",formData).subscribe((res:any) => {
      console.log(res)
      if (res.status === '200' || res.status === '201') {
        this.msg.success('操作成功');
        this.modalRef.destroy('ok');
      } else {
        this.msg.error(res.message)
      }
    })
  }
  resetForm():void{
    this.modalRef.destroy();
  }

    //拍照
takePhoto() {
  const modal = this.modal.create({
    nzTitle:  '拍照',
    nzContent: TakephotoComponent,
    nzWidth: 600,
    nzFooter:null
  })
  modal.afterClose.subscribe(res=>{
    if(res){
      this.avatarUrl2 = res;
      this.showUpdate=true;
    }else{
      const modalInstance = modal.getContentComponent(); // 获取模态框实例
      if(modalInstance.stream){
        modalInstance.stream.getTracks()[0].stop()
      }
    }
  })
}
  constructor(
    private api: ApiService,
    private http: HttpClient,
    private msg: NzMessageService,
    private modalRef: NzModalRef,
    private modal: NzModalService,
  ) { }

  nzTabPosition: NzTabPosition = 'left';

  async ngOnInit() {
    // await this.getRoleList().then(res => {
    //   this.schema.properties.role.enum = res.data.map(item => {
    //     return {label: item.roleName, value: item.id}
    //   })
    // })
    // await this.getPermitions().then(res => {
    //   this.schema.properties.dept.enum = res.data.map(item => {
    //     return {label: item.deptName, value: item.id}
    //   })
    // })
    this.showForm = true;
    this.http.post('/core/room/findPersonAndRoom', {id:this.param.id}).subscribe((res:any) => {
      console.log(res)
      if (res.status == '200') {
        this.config.data = res.data;
      }
    })

    this.getInfo();
    this.getFaceInfo();
  }


 //根据人员id查询卡信息和人员信息
 getInfo(){
  this.http.post(this.api.doorCard.queryInfo.url,{"personId":this.param.id}).subscribe((res:any)=>{
    console.log(res);
    if(res.status == 200){
      this.config2.data=res.data.cardList;
    }
  })
}

//获取人脸下发状态列表
getFaceInfo(){
  this.http.post("/core/person/queryPersonFaceUpload",{"id":this.param.id}).subscribe((res:any)=>{
    if(res.status == 200){
      this.faceConfig.data=res.data;
    }
  })
}

operate(e: any): void {
  if (e.title === '重新下发') {
    this.http.post("/core/person/updatePeopleFace",{"personId":this.param.id,"deviceCode":e.data.deviceCode}).subscribe((res:any)=>{
      this.msg.success(res.message)
    })
  }
}

  /**
 * 根据身份证号精确计算年龄
 */
 analyzeIDCard(IDCard:any):Number{
	//获取用户身份证号码
	var userCard = IDCard;
	//如果身份证号码为undefind则返回空
	if(!userCard){
		return;
	}
	//获取出生年月日
	//userCard.substring(6,10) + "-" + userCard.substring(10,12) + "-" + userCard.substring(12,14);
	var yearBirth = userCard.substring(6,10);
	var monthBirth = userCard.substring(10,12);
	var dayBirth = userCard.substring(12,14);
	//获取当前年月日并计算年龄
	var myDate = new Date();
	var monthNow = myDate.getMonth() + 1;
	var dayNow = myDate.getDay();
	var age = myDate.getFullYear() - parseInt(yearBirth);
  monthNow=Number(monthNow);
  monthBirth = parseInt(monthBirth);
  dayNow=Number(dayNow);
  dayBirth=Number(dayBirth);

	if(monthNow < monthBirth || (monthNow == monthBirth && dayNow < dayBirth)){
		age--;
	}
	//返回年龄
	return age;
}

//计算生日
getBirthdayFromIdCard(idCard:any):string {
  var birthday = "";
  if(idCard != null && idCard != ""){
    if(idCard.length == 15){
      birthday = "19"+idCard.substr(6,6);
    } else if(idCard.length == 18){
      birthday = idCard.substr(6,8);
    }
    birthday = birthday.replace(/(.{4})(.{2})/,"$1-$2-");
  }
  return birthday;
}

}
